<template>
  <div ref="chartRef" class="metric-chart"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, defineProps, onUnmounted } from 'vue';
import * as echarts from 'echarts/core';
import { GaugeChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必需的组件
echarts.use([
  GaugeChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  CanvasRenderer
]);

const props = defineProps({
  chartId: {
    type: String,
    required: true
  },
  options: {
    type: Object,
    default: () => ({
      value: 0,
      title: '指标图',
      valueColor: '#333333',
      valueSize: 60,
      titleColor: '#666666',
      titleSize: 24,
      backgroundColor: '#FFFFFF',
      borderRadius: 8,
      valueFormatter: ''
    })
  }
});

const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  
  // 销毁现有实例
  if (chartInstance) {
    chartInstance.dispose();
  }
  
  // 创建新实例
  chartInstance = echarts.init(chartRef.value);
  updateChart();
  
  window.addEventListener('resize', handleResize);
};

// 更新图表
const updateChart = () => {
  if (!chartInstance) return;
  
  const { 
    value, 
    title, 
    valueColor, 
    valueSize, 
    titleColor, 
    titleSize, 
    backgroundColor,
    valueFormatter
  } = props.options;
  
  // 格式化数值
  let formattedValue = value;
  if (valueFormatter === 'thousands') {
    formattedValue = value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  } else if (valueFormatter === 'percentage') {
    formattedValue = value + '%';
  }
  
  const option = {
    backgroundColor: backgroundColor,
    title: {
      text: title,
      left: 'center',
      top: 20,
      textStyle: {
        color: titleColor,
        fontSize: titleSize
      }
    },
    series: [
      {
        type: 'gauge',
        radius: '0%', // 隐藏仪表盘
        detail: {
          formatter: formattedValue,
          offsetCenter: [0, 10],
          fontSize: valueSize,
          color: valueColor,
          fontWeight: 'bold'
        },
        data: [{ value: Number(value) || 0 }],
        pointer: { show: false },
        axisLine: { show: false },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: { show: false }
      }
    ],
    tooltip: { show: false }
  };
  
  // 应用配置
  try {
    chartInstance.setOption(option);
  } catch (error) {
    console.error('设置图表选项时出错:', error);
  }
};

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 监听配置变化
watch(() => props.options, () => {
  if (chartInstance) {
    updateChart();
  }
}, { deep: true });

onMounted(() => {
  // 使用 nextTick 确保 DOM 已更新
  setTimeout(() => {
    initChart();
  }, 0);
});

onUnmounted(() => {
  // 清理事件监听和实例
  window.removeEventListener('resize', handleResize);
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});

// 组件卸载时释放资源
defineExpose({
  chartInstance,
  updateChart
});
</script>

<style scoped>
.metric-chart {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: v-bind('props.options.backgroundColor || "#FFFFFF"');
  border-radius: v-bind('props.options.borderRadius + "px" || "8px"');
}
</style> 